/*
 * PadronElectoralCRView.java
 */
package cr.co.tse.padronelectoral.win;

import cr.co.tse.padronelectoral.IndexSearchService;
import cr.co.tse.padronelectoral.NotMatchesWereFoundException;
import cr.co.tse.padronelectoral.domain.VotanteInfo;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * The application's main frame.
 */
public class PadronElectoralCRView extends FrameView {

    private IndexSearchService searchService = null;
    private Logger logger = Logger.getLogger(PadronElectoralCRView.class.getName());
    private InputIdJDialog inputIdJDialog = new InputIdJDialog(this.getFrame(), true);
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");

    private String formatDate(Date fromDate) {


        return dateFormat.format(fromDate);
    }

    private void initSearchComponent() {

        Properties properties = new Properties();
        FileInputStream fileInputStream = null;
        File indexDirectoryPath = null;

        try {

            fileInputStream = new FileInputStream(new File(
                    "inputfiles.properties"));
            properties.load(fileInputStream);

            indexDirectoryPath = new File(properties.getProperty("index.path.directory"));

            this.searchService = new IndexSearchService(
                    indexDirectoryPath);
        } catch (Exception e) {

            JOptionPane.showMessageDialog(this.getFrame(),
                    "Ocurrio un error al intentar acceder la base de datos: " + indexDirectoryPath + "\n Detalle del error: " + e.getMessage() + "\n" + "Por favor indique en el archivo inputfiles.properties, " + "el directorio con la base de datos.\n" + "Si no existe debera crearla ejecutanto la clase: cr.co.tse.padronelectroral.parser.ParserIndexHelper" + " e indicando los archivos de entrada en el inputfiles.properties (ver el archivo para mas detalles)\n" + "La aplicacion no puede continuar y se cerrara automaticamente!",
                    "La aplicacion no puede continuar", JOptionPane.OK_OPTION);

            logger.log(Level.SEVERE, null, e);
            System.exit(0);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException ex) {

                logger.log(Level.SEVERE, null, ex);
            }
        }
    } // initSearchComponent.

    public PadronElectoralCRView(SingleFrameApplication app) {
        super(app);

        this.initSearchComponent();
        initComponents();

        this.getFrame().addWindowListener(
                new WindowListener() {

                    public void windowActivated(WindowEvent e) {
                    }

                    public void windowClosed(WindowEvent e) {
                    }

                    public void windowClosing(WindowEvent e) {

                        // Muestra la ventana para confirmar salir.
                        showConfirmExit();

                    }

                    public void windowDeactivated(WindowEvent e) {
                    }

                    public void windowDeiconified(WindowEvent e) {
                    }

                    public void windowIconified(WindowEvent e) {
                    }

                    public void windowOpened(WindowEvent e) {
                    }
                } // WindowListener.
                );


        // status bar initialization - message timeout, idle icon and busy animation, etc
        ResourceMap resourceMap = getResourceMap();
        int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
        messageTimer = new Timer(messageTimeout, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                statusMessageLabel.setText("");
            }
        });
        messageTimer.setRepeats(false);
        int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
        for (int i = 0; i < busyIcons.length; i++) {
            busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
        }
        busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
                statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
            }
        });
        idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
        statusAnimationLabel.setIcon(idleIcon);

        // connecting action tasks to status bar via TaskMonitor
        TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
        taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {

            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                String propertyName = evt.getPropertyName();
                if ("started".equals(propertyName)) {
                    if (!busyIconTimer.isRunning()) {
                        statusAnimationLabel.setIcon(busyIcons[0]);
                        busyIconIndex = 0;
                        busyIconTimer.start();
                    }
                } else if ("message".equals(propertyName)) {
                    String text = (String) (evt.getNewValue());
                    statusMessageLabel.setText((text == null) ? "" : text);
                    messageTimer.restart();
                }
            }
        });

        // Maximizo la ventana.
        this.getFrame().setExtendedState(this.getFrame().getExtendedState() | JFrame.MAXIMIZED_BOTH);
        // Seteo el table model por defecto
        this.votantesTable.setModel(new VotantesTableModel(new ArrayList<VotanteInfo>(), this.getFrame()));
    }

    @Action
    public void showAboutBox() {
        if (aboutBox == null) {
            JFrame mainFrame = PadronElectoralCRApp.getApplication().getMainFrame();
            aboutBox = new PadronElectoralCRAboutBox(mainFrame);
            aboutBox.setLocationRelativeTo(mainFrame);
        }
        PadronElectoralCRApp.getApplication().show(aboutBox);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        votantesTable = new javax.swing.JTable();
        menuBar = new javax.swing.JMenuBar();
        javax.swing.JMenu fileMenu = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
        javax.swing.JMenu helpMenu = new javax.swing.JMenu();
        javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
        statusPanel = new javax.swing.JPanel();
        javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
        statusMessageLabel = new javax.swing.JLabel();
        statusAnimationLabel = new javax.swing.JLabel();

        mainPanel.setName("mainPanel"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        votantesTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        votantesTable.setName("votantesTable"); // NOI18N
        votantesTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                votantesTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(votantesTable);

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 733, Short.MAX_VALUE)
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
        );

        menuBar.setName("menuBar"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(cr.co.tse.padronelectoral.win.PadronElectoralCRApp.class).getContext().getResourceMap(PadronElectoralCRView.class);
        fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
        fileMenu.setName("fileMenu"); // NOI18N

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText(resourceMap.getString("findByIdMenuItem.text")); // NOI18N
        jMenuItem1.setToolTipText(resourceMap.getString("findByIdMenuItem.toolTipText")); // NOI18N
        jMenuItem1.setName("findByIdMenuItem"); // NOI18N
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem1);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem2.setText(resourceMap.getString("jMenuItem2.text")); // NOI18N
        jMenuItem2.setToolTipText(resourceMap.getString("jMenuItem2.toolTipText")); // NOI18N
        jMenuItem2.setName("jMenuItem2"); // NOI18N
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        fileMenu.add(jMenuItem2);

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(cr.co.tse.padronelectoral.win.PadronElectoralCRApp.class).getContext().getActionMap(PadronElectoralCRView.class, this);
        exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
        exitMenuItem.setName("exitMenuItem"); // NOI18N
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        fileMenu.add(exitMenuItem);

        menuBar.add(fileMenu);

        helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
        helpMenu.setName("helpMenu"); // NOI18N

        aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
        aboutMenuItem.setName("aboutMenuItem"); // NOI18N
        helpMenu.add(aboutMenuItem);

        menuBar.add(helpMenu);

        statusPanel.setName("statusPanel"); // NOI18N

        statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N

        statusMessageLabel.setName("statusMessageLabel"); // NOI18N

        statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N

        org.jdesktop.layout.GroupLayout statusPanelLayout = new org.jdesktop.layout.GroupLayout(statusPanel);
        statusPanel.setLayout(statusPanelLayout);
        statusPanelLayout.setHorizontalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 733, Short.MAX_VALUE)
            .add(statusPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(statusMessageLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 713, Short.MAX_VALUE)
                .add(statusAnimationLabel)
                .addContainerGap())
        );
        statusPanelLayout.setVerticalGroup(
            statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(statusPanelLayout.createSequentialGroup()
                .add(statusPanelSeparator, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(statusPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(statusMessageLabel)
                    .add(statusAnimationLabel))
                .add(3, 3, 3))
        );

        setComponent(mainPanel);
        setMenuBar(menuBar);
        setStatusBar(statusPanel);
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed

        Collection<VotanteInfo> votantes = null;
        String idQuery = "";
        VotantesTableModel tableModel = null;

        inputIdJDialog.setTitle("Buscar votantes por cédula");
        inputIdJDialog.setVisible(true);

        if (inputIdJDialog.isOK()) {

            idQuery = inputIdJDialog.getIdQuery();
            try {

                votantes = this.searchService.search("cedula", idQuery);
                tableModel = new VotantesTableModel(new ArrayList(votantes), this.getFrame());
                this.votantesTable.setModel(tableModel);
            } catch (NotMatchesWereFoundException ex) {

                logger.log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this.getFrame(),
                        "No se confirma un solo votante que cumpla con : " + idQuery + " \n", "Sin resultados", JOptionPane.OK_OPTION);
            } catch (Exception ex) {

                logger.log(Level.SEVERE, null, ex);
            }

        }
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
        this.showConfirmExit();
    }//GEN-LAST:event_exitMenuItemActionPerformed

    private void votantesTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_votantesTableMouseClicked

        int rowSelected = 0;
        VotanteInfo votante = null;
        ShowVotanteDialog showVotanteDialog = null;

        if (2 == evt.getClickCount()) {

            // Determine the row selected.
            rowSelected = (evt.getY() / this.votantesTable.getRowHeight());
            votante = this.getVotanteFromModel(rowSelected);
            if (null != votante) {

                showVotanteDialog = new ShowVotanteDialog(this.getFrame(), false);
                showVotanteDialog.setTitle("Mostrando información de: " + votante.getNombre() + " " + votante.getCedula());
                showVotanteDialog.setVotanteInfo(votante);
                showVotanteDialog.setVisible(true);
            }
        }
    }//GEN-LAST:event_votantesTableMouseClicked

    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed

        SearchByNameDialog searchByNameJFrame =
                new SearchByNameDialog(this.getFrame(), true);

        String name;
        String lastName1;
        String lastName2;
        List<String> fields = new ArrayList<String>();
        List<String> queries = new ArrayList<String>();

        searchByNameJFrame.setTitle("Busqueda por nombre");
        searchByNameJFrame.setVisible(true);

        Collection<VotanteInfo> votantes;
        VotantesTableModel tableModel;


        if (searchByNameJFrame.isOK()) {


            name = searchByNameJFrame.getName();
            if (name.length() > 0) {
                fields.add("nombre");
                queries.add(name);
            }

            lastName1 = searchByNameJFrame.getLastName1();
            if (lastName1.length() > 0) {
                fields.add("apellido1");
                queries.add(lastName1);
            }

            lastName2 = searchByNameJFrame.getLastName2();
            if (lastName2.length() > 0) {
                fields.add("apellido2");
                queries.add(lastName2);
            }


            try {

                logger.log(Level.INFO, "query: " + queries);
                if (queries.size() > 0) {
                    votantes = this.searchService.search((String[]) fields.toArray(new String[]{}), (String[]) queries.toArray(new String[]{}));
                    tableModel = new VotantesTableModel(new ArrayList(votantes), this.getFrame());
                    this.votantesTable.setModel(tableModel);
                }
            } catch (NotMatchesWereFoundException ex) {

                logger.log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this.getFrame(),
                        "No se confirma un solo votante que cumpla con los criterios \n", "Sin resultados", JOptionPane.OK_OPTION);
            } catch (Exception ex) {

                logger.log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_jMenuItem2ActionPerformed

    private VotanteInfo getVotanteFromModel(int row) {

        VotanteInfo votante = null;
        VotantesTableModel votantesTableModel = VotantesTableModel.class.cast(this.votantesTable.getModel());
        votante = votantesTableModel.getVotante(row);
        return votante;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenuBar menuBar;
    private javax.swing.JLabel statusAnimationLabel;
    private javax.swing.JLabel statusMessageLabel;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTable votantesTable;
    // End of variables declaration//GEN-END:variables
    private final Timer messageTimer;
    private final Timer busyIconTimer;
    private final Icon idleIcon;
    private final Icon[] busyIcons = new Icon[15];
    private int busyIconIndex = 0;
    private JDialog aboutBox;

    /**
     * Muestra el dialogo de confirma salvar.
     *
     */
    private void showConfirmExit() {

        int option = JOptionPane.showConfirmDialog(null,
                "Esta seguro que desea abandonar el programa", "Salir",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE);

        if (JOptionPane.YES_OPTION == option) {
            try {
                this.searchService.closeSearcher();
            } catch (IOException ex) {
                logger.log(Level.SEVERE, null, ex);
                JOptionPane.showMessageDialog(this.getFrame(),
                        "No se pudo cerrar la base de datos correctamente\n" + "Detalle del error: " + ex.getMessage(), "Error", JOptionPane.OK_OPTION);
            }
            this.getFrame().setVisible(false);
            System.exit(0);
        }
    } // showConfirmExit.
}
